<?php

namespace addons\facrm\controller;

use EasyWeChat\Factory;
use think\Config;
use think\Db;
use think\Queue;

/**
 * 定时任务
 * @internal
 */
class Autotask extends \think\addons\Controller
{
    protected $noNeedLogin = ["*"];
    protected $layout = '';

    public function _initialize()
    {
        set_time_limit(0);
        parent::_initialize();

        if (!$this->request->isCli()) {
            $this->error('只允许在终端进行操作!');
        }
    }

    /**
     * 定时任务逻辑
     */
    public function index()
    {
        $this->flowcustomer();
        $this->flowbusiness();
        $this->expirecontract();
        $this->expirecustomer();
        $this->flowclues();
    }

    /**
     * 待跟进客户提醒
     */
    public function flowcustomer()
    {

        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        $customerModel = model('\app\admin\model\facrm\Customer');
        //需要联系客户
        $communicate = $customerModel->where('next_time', 'between', [1, $end_time])
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($communicate as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\CustomerJob", [
                'key' => 'notice_flow_customer',//待跟进通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;
    }

    /**
     * 待跟进线索提醒
     */
    public function flowclues()
    {

        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        $cluesModel = model('\app\admin\model\facrm\Clues');
        //需要联系线索
        $communicate = $cluesModel->where('next_time', 'between', [1, $end_time])
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($communicate as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\CluesJob", [
                'key' => 'notice_flow_clues',//待跟进通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;
    }

    /**
     * 待跟进商机提醒
     */
    public function flowbusiness()
    {
        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        $thisModel = model('\app\admin\model\facrm\Business');
        //需要联系
        $communicate = $thisModel->where('next_time', 'between', [1, $end_time])
            ->where('is_end', 0)
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($communicate as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\BusinessrJob", [
                'key' => 'notice_flow_business',//待跟进通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;
    }

    /**
     * 将过期合同（提前三十天）
     */
    public function expirecontract()
    {

        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        $thisModel = model('\app\admin\model\facrm\Contract');
        //需要联系
        $communicate = $thisModel->where('end_time', 'between', [1, $end_time + (30 * 86400)])
            ->where('expire_handle', 0)
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($communicate as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\ContractJob", [
                'key' => 'notice_expire_contract',//待跟进通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;

    }


    /**
     * 将要过期客户提醒
     */
    public function expirecustomer()
    {

        $config = get_addon_config('facrm');
        //判断是否开启过期的功能
        if ($config['lose_day1'] <= 0 && ($config['lose_day2'] <= 0)) {
            echo "done none";
            return;
        }

        $thisModel = model('\app\admin\model\facrm\Customer');

        $lists = $thisModel->getLoseWhere($config, 1)
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($lists as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\CustomerJob", [
                'key' => 'notice_expire_ccustomer',//客户将过期通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;
    }


    /**
     * 云呼记录同步云呼建议1个小时执行一次【废弃已改用事件通知】
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function calllog()
    {
        $this->key = "cloudcall";
        //获取云呼配置
        $all_types = \addons\facrm\library\cloudcall\Call::getProviders();
        $keys = "";
        foreach ($all_types as $v) {
            $keys .= $keys ? ',' . $this->key . $v : $this->key . $v;
        }
        $settingModel = new \app\admin\model\facrm\Setting();
        $setting = $settingModel->where('key', 'in', $keys)->where('status', 1)->find();//只找一条云呼通道

        if (!$setting) {
            $this->error(__("云呼通道没有配置，请先配置"));
        }
        //获取坐席

        $setting = $setting->toArray();
        $setting['key'] = $setting['describe'];
        $setting = array_merge($setting, $setting['values']);
        $call = \addons\facrm\library\cloudcall\Call::instance($setting);


        $calldata['beginTime'] = datetime(time() - (86400 * 1), 'Y-m-d H:i:s');//开始时间
        $calldata['endTime'] = datetime(time(), 'Y-m-d H:i:s');//结束时间


        $result = $call->getCallRecord($calldata);
        if (!$result) {
            $this->error($call->getError());
        }
        $result = json_decode($result, true);
        if (isset($result['success']) && $result['success'] && $result['data']) {
            $cloudcallLog = new \app\admin\model\facrm\CloudcallLog();
            foreach ($result['data'] as $r) {
                if (!$r['ACTION_ID']) continue;

                $log = $cloudcallLog->where('action_id', $r['ACTION_ID'])->where('status', 0)->find();
                if (!$log) continue;

                $log->call_no = $r['CALL_NO'];
                $log->status = $r['STATUS'] == 'dealing' ? 1 : -1;
                $log->record_file = $r['FILE_SERVER'] . '/' . $r['RECORD_FILE_NAME'];
                $log->call_time_length = $r['CALL_TIME_LENGTH'];

                $log->save();
            }

        }
    }

    /**
     * 同步微信员工、客户
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function synwx()
    {
        set_time_limit(0);
        $key = "work_weixin_set";
        $settingModel = new \app\admin\model\facrm\Setting();
        $row = $settingModel->where('key', $key)->cache(1800)->find();
        if (!$row) {
            echo "企业微信未配置";
            return;
        }
        $values = json_decode($row['values'], true);//获取器不知道为什么失效了
        if (!$values) {
            echo "企业微信未配置1";
            return;
        }


        $config = [
            'corp_id' => $values['corp_id'],
            'secret' => $values['agent_secret'],
            'agent_id' => $values['agent_id'],
            //'agent_secret' => $values['agent_secret'],
        ];
        try {
            $app = Factory::work($config);
            $result = $app->user->getDetailedDepartmentUsers(1, true);
        } catch (\Exception $e) {
            $this->error($e->getMessage());

        }
        if (!$result || $result['errcode'] != '0') {
            $errmsg = isset($result['errmsg']) ? $result['errmsg'] : 'null';
            echo "获取失败：" . $errmsg;
            return;
        }
        $userlist = $result['userlist'];
        $result = 0;
        foreach ($userlist as $user) {
            //判断系统是否存在
            $qywxUser = \app\admin\model\facrm\qywx\User::getUser($user['userid'], $values, $user);
            if ($qywxUser) $result++;
        }
        echo "同步更新企业微信员工{$result}条";
        /*-----------同步员工end----------------*/

        $this->synwxcustomer($values);
        return;


    }


    protected function synwxcustomer($values,$page=1,$next_cursor="",$is_action=true){
        $c_config = [
            'corp_id' => $values['corp_id'],
            'secret' => $values['customer_secret'], // 客户的 secret
        ];
        $appc = Factory::work($c_config);
        $qywxUserModel = new  \app\admin\model\facrm\qywx\User();
        $userList = $qywxUserModel->page($page,100)->order('id asc')->column('admin_id','userid');
        if (!$userList){
            echo "同步客户完成";
            return;
        }

        $contactsModel = new \app\admin\model\facrm\qywx\Contacts();

        $externalcontact = new \addons\facrm\library\extend\easywechat\Externalcontact($appc);
        try {
            //批量查询客户详情
            $externalList = $externalcontact->batch(array_keys($userList),$next_cursor,100);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        if (!$externalList || $externalList['errcode'] != '0' ){
            echo $externalList['errmsg'];

        }
        if ($externalList['external_contact_list']&&count($externalList['external_contact_list'])>0){
            $syn_number=count($externalList['external_contact_list']);
            foreach ($externalList['external_contact_list'] as $row) {
                $follow_user = $row['follow_info'];
                $admin_id=isset($userList[$follow_user['userid']])?$userList[$follow_user['userid']]:0;

                $contactsModel->getContacts($row, $values, ['admin_id' => $admin_id]);
            }
            if (isset($externalList['next_cursor'])&&$externalList['next_cursor']){
                $syn_number+=$this->synwxcustomer($values,$page,$externalList['next_cursor'],false);
            }
        }
        if (!$is_action){
            return $syn_number;
        }
        echo "本次同步更新{$syn_number}条客户数据";
        return $this->synwxcustomer($values,$page+1);
    }
}